package com.shb.jutils.commons;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import com.shb.jutils.pojo.Mail;
import com.shb.jutils.pojo.MyAuthenticator;

public class SendMailUtil {

	private SendMailUtil(){}
	
	public static boolean sendMail(Mail mail){
		Properties p = new Properties();
		p.put("mail.smtp.host", mail.getMailServerHost());
		p.put("mail.smtp.port", mail.getMailServerPort());
		p.put("mail.smtp.auth", mail.isValidate() ? "true" : "false");
		if(mail.isSSL()){
			p.put("mail.smtp.starttls.enable", "true");
			p.put("mail.smtp.socketFactory.fallback", "false");
			p.put("mail.smtp.socketFactory.port", mail.getMailServerPort());
			
		}
		Authenticator auth = null;
		if(mail.isValidate()){
			auth = new MyAuthenticator(mail.getFromAddress(), mail.getUserPass());
		}
		try{
			Session session = Session.getDefaultInstance(p, auth);
			Message message = new MimeMessage(session);
			Address from = new InternetAddress(mail.getFromAddress());
			Address to = new InternetAddress(mail.getToAddress());
			message.setFrom(from);
			message.setRecipient(Message.RecipientType.TO, to);
			message.setSubject(mail.getSubject());
			message.setSentDate(new Date());
			if(mail.isHtml()){
				Multipart m = new MimeMultipart();
				BodyPart bp=new MimeBodyPart();
				bp.setContent(mail.getContent(), "text/plain;charset=utf-8");
				m.addBodyPart(bp);
				message.setContent(m);
			}else {
				message.setText(mail.getContent());
			}
			Transport.send(message);
			return true;
		}catch (MessagingException e){
			e.printStackTrace();
			try {
				MimeUtility.decodeText(e.getMessage());
			} catch (UnsupportedEncodingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			return false;
		}
	}
}
